import { useEffect, useState } from 'react';
import { Card, Image, Typography, Pagination, Row, Col, Spin } from 'antd';
import axios from 'axios';
import { Link } from 'react-router-dom'; // 导入 Link
import './index.css';
import headerImage from '../../../assets/top_img.jpg';
import { Footer } from 'antd/es/layout/layout';

const { Meta } = Card;
const { Title } = Typography;

const SpeechFirstPage = () => {
  const [books, setBooks] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [loading, setLoading] = useState(true); 
  const booksPerPage = 12;

  // useEffect(() => {
  //   const fetchBooks = async () => {
  //     try {
  //       const response = await axios.get('/api/dialogue-books');
  //       console.log('Fetched books:', response.data); 

  //       // 提取实际的书籍数据数组
  //       const actualBooks = Array.isArray(response.data) && response.data.length > 1 ? response.data[1] : [];
  //       setBooks(actualBooks);
  //     } catch (error) {
  //       console.error('Error fetching books:', error);
  //     } finally {
  //       setLoading(false); 
  //     }
  //   };
  useEffect(() => {
    const fetchBooks = async () => {
      try {
        const response = await axios.get('/api/dialogue-books');
        console.log('Fetched books:', response.data); 

        // 假设 response.data 直接就是书籍数组
        const actualBooks = Array.isArray(response.data) ? response.data : [];
        setBooks(actualBooks);
      } catch (error) {
        console.error('Error fetching books:', error);
      } finally {
        setLoading(false); 
      }
    };

    fetchBooks();
  }, []);

  const indexOfLastBook = currentPage * booksPerPage;
  const indexOfFirstBook = indexOfLastBook - booksPerPage;
  const currentBooks = books.slice(indexOfFirstBook, indexOfLastBook);

  const paginate = pageNumber => setCurrentPage(pageNumber);

  return (
    <div className='book-list-container'>
      {/* 在最上方添加图片 */}
      <div style={{ marginBottom: '20px' }}> {/* 添加底部间距 */}
        <Image
          src={headerImage} // 使用导入的图片变量
          alt="Header Image"
          preview={false} // 禁用预览功能
          style={{
            maxWidth: '100%', // 设置最大宽度为100%
            height: 'auto', // 高度自动调整以保持比例
            display: 'block', // 使图片成为块级元素
            margin: '0 auto', // 水平居中
          }}
        />
      </div>
      <Title level={2}>Choose What You Want To Exercise!</Title>
      {loading ? (
        <Spin size="large" style={{ margin: '0 auto', display: 'block' }} />
      ) : (
        <>
          <Row gutter={[24, 24]} className="row-of-cards">
            {Array.isArray(currentBooks) && currentBooks.map(book => (
              <Col key={book.bookId} xs={24} sm={12} md={8} lg={6} xl={6} className="card-item">
                <Link to={`/dialogue/${book.bookId}/chapter`} key={book.bookId}>
                  <Card
                    cover={<Image
                      src={`data:image/png;base64,${book.pictureBase64 || ''}`} // 添加默认值
                      alt={book.title}
                      fallback="https://via.placeholder.com/150" // 默认图片
                    />}
                    title={book.title}
                    bordered={false}
                    className="small-card-content"
                  >
                    <Meta description={book.description} />
                  </Card>
                </Link>
                <div className="card-footer">
                  {/* 分页或其他元素 */}
                </div>
              </Col>
            ))}
          </Row>
          <Pagination
            current={currentPage}
            total={books.length}
            pageSize={booksPerPage}
            onChange={paginate}
            showSizeChanger={false}
            style={{ textAlign: 'center', marginTop: '20px' }}
          />
        </>
      )}
      <Footer style={{ 
        marginTop: '20px', 
        textAlign: 'center', 
        backgroundColor: '#a1daeb', 
        padding: '20px 0', 
        color: '#ffffff' 
      }}>
        <p>© 2024 Reora</p>
        <p>Contact me: <a href="mailto:981706712@qq.com">981706712@qq.com</a></p>
      </Footer>
    </div>
  );
};

export default SpeechFirstPage;